import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:qm_line/model/response.dart';
import 'package:qm_line/qm_line.dart';
import 'package:qm_line/qm_line_platform_interface.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _qmLinePlugin = QmLine();

  @override
  void initState() {
    super.initState();
    _qmLinePlugin.addEventHandler(onInitScuuess: (QMResponse argument) async {
      print('初始化成功');
      Fluttertoast.showToast(msg: '初始化成功');
    }, onInitFailed: (QMResponse argument) async {
      print('初始化失败！错误信息：${argument.errorMessage}');
      Fluttertoast.showToast(msg: '初始化失败！错误信息：${argument.errorMessage}');
    }, newMessage: (dynamic argument) async {
      print('收到消息：$argument');
      Fluttertoast.showToast(msg: '收到消息：$argument');
    }, customOnline: (dynamic argument) async {
      print('客服在线');
      Fluttertoast.showToast(msg: '客服在线');
    }, customOffline: (dynamic argument) async {
      print('客服离线');
      Fluttertoast.showToast(msg: '客服离线');
    }, customClaim: (dynamic argument) async {
      print('会话被坐席领取');
      Fluttertoast.showToast(msg: '会话被坐席领取');
    }, customFinish: (dynamic argument) async {
      print('结束会话');
      Fluttertoast.showToast(msg: '结束会话');
    }, customQueue: (dynamic argument) async {
      print('排队人数');
      Fluttertoast.showToast(msg: '排队人数');
    }, customAgentInfo: (dynamic argument) async {
      print('坐席信息');
      Fluttertoast.showToast(msg: '坐席信息');
    }, customInvestigate: (dynamic argument) async {
      print('满意度推送');
      Fluttertoast.showToast(msg: '满意度推送');
    }, customVIP: (dynamic argument) async {
      print('专属坐席不在线通知');
      Fluttertoast.showToast(msg: '专属坐席不在线通知');
    }, changeCustomStatus: (dynamic argument) async {
      print('坐席正在输入');
      Fluttertoast.showToast(msg: '坐席正在输入');
    }, withdrawMessageStatus: (dynamic argument) async {
      print('撤回消息');
      Fluttertoast.showToast(msg: '撤回消息');
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            TextButton(onPressed: initSDK, child: const Text('初始化SDK')),
            TextButton(onPressed: quitSDK, child: const Text('退出')),
            TextButton(onPressed: beginChatSession, child: const Text('开启会话')),
            TextButton(onPressed: getMessageList, child: const Text('获取消息列表')),
            TextButton(onPressed: sendTextMessage, child: const Text('发送文本消息')),
            TextButton(onPressed: getUnreadMsgCount, child: const Text('获取未读消息数')),
            TextButton(onPressed: getUnreadMsgList, child: const Text('获取未读消息列表')),
          ],
        ),
      ),
    );
  }

  void initSDK() {
    _qmLinePlugin.switchServiceRoute(QMServiceLine.tencent);
    _qmLinePlugin.initSDK('ec54eca0-6dcb-11ec-a29f-ffc004a399d1', '测试账号', '202068').then((response) {
      if (response.isSuccess()) {
        Fluttertoast.showToast(msg: '初始化成功');
      } else {
        Fluttertoast.showToast(msg: '初始化失败！错误信息：${response.errorMessage}');
      }
    });
  }

  void quitSDK() {
    _qmLinePlugin.quitSDK();
  }

  void beginChatSession() {
    Map param = Map();
    param['customField'] = {'用户名': '测试帐号', '手机': '13148762314', '邮箱': '916050884@qq.com', '设备': Platform.isAndroid ? 'Android' : 'iOS'};
    _qmLinePlugin.beginChatSession('10054601', param).then((response) {
      if (response.isSuccess()) {
        Fluttertoast.showToast(msg: '开启会话成功！');
      } else {
        Fluttertoast.showToast(msg: '开启会话失败！错误信息：${response.errorMessage}');
      }
    });
  }

  void getMessageList() {
    _qmLinePlugin.getMessageList(1).then((response) {
      var data = response.data as List<Object?>?;
      if (data == null || data.isEmpty)
        print("empty list");
      else {
        print("共${data.length}条消息");
        print("=========== 消息列表 START =============");
        data.forEach((element) {
          // print(element);
          element = element as Map<Object?, Object?>;
          print("id: ${element['id']}, timestamp: ${element['createdTime']}, text: ${element['text']}");
        });
        print("=========== 消息列表 END =============");
      }
    });
  }

  void sendTextMessage() {
    _qmLinePlugin.sendTextMessage('再发1条').then((response) {
      print(response);
      if (response.isSuccess()) {
        print('发送成功');
      } else {
        print('发送失败');
      }
    });
  }

  void getUnreadMsgCount() {
    _qmLinePlugin.switchServiceRoute(QMServiceLine.tencent);
    _qmLinePlugin.getUnreadMessageCount('ec54eca0-6dcb-11ec-a29f-ffc004a399d1', '测试账号', '202068').then((rsp) async {
      print("got unread msg count: ${rsp.data}");
    });
  }

  void getUnreadMsgList() async {
    String afterMsgId = "c5e40f05-0bcc-40ac-ad9e-f9513f8abf6b";
    var rsp = await _qmLinePlugin.getUnreadMessageList(afterMsgId);
    var data = rsp.data as List<Object?>?;
    if (data == null || data.isEmpty) {
      print("no more unread msg");
    } else {
      print("未读消息列表数量: ${data.length}");
      print("=========== 未读消息列表 START =============");
      data.forEach((element) {
        element = element as Map<Object?, Object?>;
        print("id: ${element['id']}, timestamp: ${element['createdTime']}, text: ${element['text']}");
      });
      print("=========== 未读消息列表 END =============");
    }
  }
}
